package com.hui.qiniucloud.controller;

import com.hui.qiniucloud.entity.Result;
import com.hui.qiniucloud.entity.AICharacter;
import com.hui.qiniucloud.service.IDoubaoUniversalService;
import com.hui.qiniucloud.service.ICharacterService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Mono;

import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api/doubao")
@CrossOrigin(origins = "*")
@RequiredArgsConstructor
@Tag(name = "豆包通用大模型", description = "豆包大模型通用接口，提供快速非流式响应")
public class DoubaoUniversalController {

    @Autowired
    private IDoubaoUniversalService doubaoUniversalService;

    @Autowired
    private ICharacterService characterService;

    /**
     * 简单聊天接口
     */
    @Operation(summary = "简单聊天",
               description = "发送消息给豆包大模型，获取快速响应",
               requestBody = @io.swagger.v3.oas.annotations.parameters.RequestBody(
                   description = "聊天请求参数",
                   content = @Content(
                       mediaType = "application/json",
                       examples = @io.swagger.v3.oas.annotations.media.ExampleObject(
                           name = "简单聊天示例",
                           summary = "基础聊天请求",
                           value = """
                               {
                                 "message": "你好，请介绍一下你自己"
                               }
                               """
                       )
                   )
               ))
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "成功获取AI回复",
                    content = @Content(mediaType = "application/json",
                                     examples = @io.swagger.v3.oas.annotations.media.ExampleObject(
                                         name = "成功响应示例",
                                         value = """
                                             {
                                               "success": true,
                                               "response": "你好！我是豆包AI助手，很高兴为您服务...",
                                               "timestamp": 1695123456789
                                             }
                                             """
                                     ))),
        @ApiResponse(responseCode = "400", description = "请求参数错误"),
        @ApiResponse(responseCode = "500", description = "AI服务异常")
    })
    @PostMapping("/chat")
    public Mono<ResponseEntity<Map<String, Object>>> chat(
            @Parameter(description = "聊天消息", required = true)
            @RequestBody @Valid Map<String, String> request) {

        String message = request.get("message");
        if (message == null || message.trim().isEmpty()) {
            return Mono.just(ResponseEntity.badRequest()
                    .body(Map.of("error", "消息内容不能为空")));
        }

        return doubaoUniversalService.chat(message)
                .map(response -> {
                    Map<String, Object> result = new HashMap<>();
                    result.put("success", true);
                    result.put("response", response);
                    result.put("timestamp", System.currentTimeMillis());
                    return ResponseEntity.ok(result);
                })
                .onErrorReturn(ResponseEntity.internalServerError()
                        .body(Map.of("error", "AI服务暂时不可用，请稍后重试")));
    }

    /**
     * 带系统提示的聊天接口
     */
    @Operation(summary = "带系统提示的聊天",
               description = "使用自定义系统提示词与豆包大模型对话",
               requestBody = @io.swagger.v3.oas.annotations.parameters.RequestBody(
                   description = "包含系统提示的聊天请求",
                   content = @Content(
                       mediaType = "application/json",
                       examples = @io.swagger.v3.oas.annotations.media.ExampleObject(
                           name = "系统提示聊天示例",
                           summary = "带系统提示的聊天请求",
                           value = """
                               {
                                 "message": "如何在Java中实现单例模式？",
                                 "systemPrompt": "你是一个专业的编程助手，擅长解答技术问题，请提供详细和准确的代码示例"
                               }
                               """
                       )
                   )
               ))
    @PostMapping("/chat/system")
    public Mono<ResponseEntity<Map<String, Object>>> chatWithSystem(
            @Parameter(description = "聊天请求，包含消息和系统提示")
            @RequestBody @Valid Map<String, String> request) {

        String message = request.get("message");
        String systemPrompt = request.get("systemPrompt");

        if (message == null || message.trim().isEmpty()) {
            return Mono.just(ResponseEntity.badRequest()
                    .body(Map.of("error", "消息内容不能为空")));
        }

        return doubaoUniversalService.chatWithSystem(message, systemPrompt)
                .map(response -> {
                    Map<String, Object> result = new HashMap<>();
                    result.put("success", true);
                    result.put("response", response);
                    result.put("systemPrompt", systemPrompt != null ? systemPrompt : "");
                    result.put("timestamp", System.currentTimeMillis());
                    return ResponseEntity.ok(result);
                })
                .onErrorReturn(ResponseEntity.internalServerError()
                        .body(Map.of("error", "AI服务暂时不可用，请稍后重试")));
    }

    /**
     * 带历史记录的聊天接口
     */
    @Operation(summary = "上下文聊天",
               description = "支持聊天历史记录的对话接口",
               requestBody = @io.swagger.v3.oas.annotations.parameters.RequestBody(
                   description = "包含历史记录的聊天请求",
                   content = @Content(
                       mediaType = "application/json",
                       examples = @io.swagger.v3.oas.annotations.media.ExampleObject(
                           name = "上下文聊天示例",
                           summary = "带历史记录的聊天请求",
                           value = """
                               {
                                 "message": "能举个具体的应用例子吗？",
                                 "systemPrompt": "你是一个有用的AI助手",
                                 "chatHistory": [
                                   {
                                     "role": "user",
                                     "content": "什么是机器学习？"
                                   },
                                   {
                                     "role": "assistant",
                                     "content": "机器学习是人工智能的一个子领域，它使用算法和统计模型让计算机系统能够从数据中学习和改进..."
                                   }
                                 ]
                               }
                               """
                       )
                   )
               ))
    @PostMapping("/chat/context")
    public Mono<ResponseEntity<Map<String, Object>>> chatWithContext(
            @Parameter(description = "聊天请求，包含消息、系统提示和历史记录")
            @RequestBody @Valid Map<String, Object> request) {

        String message = (String) request.get("message");
        String systemPrompt = (String) request.get("systemPrompt");
        List<Map<String, String>> chatHistory = (List<Map<String, String>>) request.get("chatHistory");

        if (message == null || message.trim().isEmpty()) {
            return Mono.just(ResponseEntity.badRequest()
                    .body(Map.of("error", "消息内容不能为空")));
        }

        return doubaoUniversalService.chat(message, systemPrompt, chatHistory)
                .map(response -> {
                    Map<String, Object> result = new HashMap<>();
                    result.put("success", true);
                    result.put("response", response);
                    result.put("historyLength", chatHistory != null ? chatHistory.size() : 0);
                    result.put("timestamp", System.currentTimeMillis());
                    return ResponseEntity.ok(result);
                })
                .onErrorReturn(ResponseEntity.internalServerError()
                        .body(Map.of("error", "AI服务暂时不可用，请稍后重试")));
    }

    /**
     * 高级聊天接口 - 支持自定义参数
     */
//    @Operation(summary = "高级聊天",
//               description = "支持自定义模型、温度等参数的聊天接口",
//               requestBody = @io.swagger.v3.oas.annotations.parameters.RequestBody(
//                   description = "高级聊天请求参数",
//                   content = @Content(
//                       mediaType = "application/json",
//                       examples = @io.swagger.v3.oas.annotations.media.ExampleObject(
//                           name = "高级聊天示例",
//                           summary = "自定义参数的聊天请求",
//                           value = """
//                               {
//                                 "message": "写一个Python函数来计算斐波那契数列",
//                                 "systemPrompt": "你是一个专业的编程助手，请提供清晰、优化的代码",
//                                 "model": "doubao-lite-4k",
//                                 "temperature": 0.2,
//                                 "maxTokens": 2048,
//                                 "chatHistory": []
//                               }
//                               """
//                       )
//                   )
//               ))
//    @PostMapping("/chat/advanced")
    public Mono<ResponseEntity<Map<String, Object>>> chatAdvanced(
            @Parameter(description = "高级聊天请求")
            @RequestBody @Valid AdvancedChatRequest request) {

        if (request.getMessage() == null || request.getMessage().trim().isEmpty()) {
            return Mono.just(ResponseEntity.badRequest()
                    .body(Map.of("error", "消息内容不能为空")));
        }

        return doubaoUniversalService.chatWithCustomParams(
                request.getMessage(),
                request.getSystemPrompt(),
                request.getChatHistory(),
                request.getModel(),
                request.getTemperature(),
                request.getMaxTokens()
        )
                .map(response -> {
                    Map<String, Object> result = new HashMap<>();
                    result.put("success", true);
                    result.put("response", response);
                    result.put("model", request.getModel() != null ? request.getModel() : "default");
                    result.put("temperature", request.getTemperature() != null ? request.getTemperature() : 0.7);
                    result.put("maxTokens", request.getMaxTokens() != null ? request.getMaxTokens() : 2000);
                    result.put("timestamp", System.currentTimeMillis());
                    return ResponseEntity.ok(result);
                })
                .onErrorReturn(ResponseEntity.internalServerError()
                        .body(Map.of("error", "AI服务暂时不可用，请稍后重试")));
    }

    /**
     * 角色扮演聊天接口
     */
    @Operation(summary = "角色扮演聊天",
               description = "以指定角色的身份与豆包大模型对话",
               requestBody = @io.swagger.v3.oas.annotations.parameters.RequestBody(
                   description = "角色扮演聊天请求",
                   content = @Content(
                       mediaType = "application/json",
                       examples = @io.swagger.v3.oas.annotations.media.ExampleObject(
                           name = "角色扮演聊天示例",
                           summary = "扮演哈利波特聊天",
                           value = """
                               {
                                 "message": "你好，能告诉我关于霍格沃茨的事吗？",
                                 "characterId": "harry_potter",
                                 "chatHistory": []
                               }
                               """
                       )
                   )
               ))
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "成功获取角色扮演回复",
                    content = @Content(mediaType = "application/json",
                                     examples = @io.swagger.v3.oas.annotations.media.ExampleObject(
                                         name = "角色扮演响应示例",
                                         value = """
                                             {
                                               "success": true,
                                               "response": "你好！当然可以。霍格沃茨是一所神奇的魔法学校...",
                                               "character": {
                                                 "id": "harry_potter",
                                                 "name": "哈利·波特"
                                               },
                                               "timestamp": 1695123456789
                                             }
                                             """
                                     ))),
        @ApiResponse(responseCode = "400", description = "请求参数错误"),
        @ApiResponse(responseCode = "404", description = "角色不存在"),
        @ApiResponse(responseCode = "500", description = "AI服务异常")
    })
    @PostMapping("/chat/character")
    public Mono<ResponseEntity<Map<String, Object>>> chatWithCharacter(
            @Parameter(description = "角色扮演聊天请求")
            @RequestBody @Valid CharacterChatRequest request) {

        String message = request.getMessage();
        String characterId = request.getCharacterId();

        if (message == null || message.trim().isEmpty()) {
            return Mono.just(ResponseEntity.badRequest()
                    .body(Map.of("error", "消息内容不能为空")));
        }

        if (characterId == null || characterId.trim().isEmpty()) {
            return Mono.just(ResponseEntity.badRequest()
                    .body(Map.of("error", "角色ID不能为空")));
        }

        // 获取角色信息
        AICharacter character = characterService.getCharacterById(characterId);
        if (character == null) {
            return Mono.just(ResponseEntity.status(404)
                    .body(Map.of("error", "角色不存在: " + characterId)));
        }

        return doubaoUniversalService.chatWithCharacter(message, character, request.getChatHistory())
                .map(response -> {
                    Map<String, Object> result = new HashMap<>();
                    result.put("success", true);
                    result.put("response", response);
                    result.put("character", Map.of(
                        "id", character.getId(),
                        "name", character.getName(),
                        "description", character.getDescription()
                    ));
                    result.put("historyLength", request.getChatHistory() != null ? request.getChatHistory().size() : 0);
                    result.put("timestamp", System.currentTimeMillis());
                    return ResponseEntity.ok(result);
                })
                .onErrorReturn(ResponseEntity.internalServerError()
                        .body(Map.of("error", "AI服务暂时不可用，请稍后重试")));
    }

    /**
     * 健康检查接口
     */
    @Operation(summary = "服务健康检查",
               description = "检查豆包大模型服务是否可用")
    @GetMapping("/health")
    public Mono<ResponseEntity<Map<String, Object>>> healthCheck() {
        return doubaoUniversalService.checkHealth()
                .map(isHealthy -> {
                    Map<String, Object> result = new HashMap<>();
                    result.put("healthy", isHealthy);
                    result.put("service", "豆包大模型");
                    result.put("timestamp", System.currentTimeMillis());
                    return ResponseEntity.ok(result);
                })
                .onErrorReturn(ResponseEntity.ok(Map.of(
                        "healthy", false,
                        "service", "豆包大模型",
                        "timestamp", System.currentTimeMillis()
                )));
    }

    /**
     * 高级聊天请求参数类
     */
    public static class AdvancedChatRequest {
        @NotBlank(message = "消息不能为空")
        private String message;

        private String systemPrompt;

        private List<Map<String, String>> chatHistory;

        private String model;

        @Min(value = 0, message = "温度值不能小于0")
        @Max(value = 1, message = "温度值不能大于1")
        private Double temperature;

        @Min(value = 1, message = "最大token数不能小于1")
        @Max(value = 4000, message = "最大token数不能大于4000")
        private Integer maxTokens;

        // Getters and Setters
        public String getMessage() { return message; }
        public void setMessage(String message) { this.message = message; }

        public String getSystemPrompt() { return systemPrompt; }
        public void setSystemPrompt(String systemPrompt) { this.systemPrompt = systemPrompt; }

        public List<Map<String, String>> getChatHistory() { return chatHistory; }
        public void setChatHistory(List<Map<String, String>> chatHistory) { this.chatHistory = chatHistory; }

        public String getModel() { return model; }
        public void setModel(String model) { this.model = model; }

        public Double getTemperature() { return temperature; }
        public void setTemperature(Double temperature) { this.temperature = temperature; }

        public Integer getMaxTokens() { return maxTokens; }
        public void setMaxTokens(Integer maxTokens) { this.maxTokens = maxTokens; }
    }

    /**
     * 角色扮演聊天请求参数类
     */
    public static class CharacterChatRequest {
        @NotBlank(message = "消息不能为空")
        private String message;

        @NotBlank(message = "角色ID不能为空")
        private String characterId;

        private List<Map<String, String>> chatHistory;

        // Getters and Setters
        public String getMessage() { return message; }
        public void setMessage(String message) { this.message = message; }

        public String getCharacterId() { return characterId; }
        public void setCharacterId(String characterId) { this.characterId = characterId; }

        public List<Map<String, String>> getChatHistory() { return chatHistory; }
        public void setChatHistory(List<Map<String, String>> chatHistory) { this.chatHistory = chatHistory; }
    }
}